<template>
  <view class="container">
    <!-- 顶部导航栏 -->
<!--    <view class="nav-bar">
      <view class="nav-left" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <text class="nav-title">拍照设计</text>
      <view class="nav-right">
        <text class="help-icon" @click="showTips">?</text>
      </view>
    </view> -->

    <!-- 主要内容区域 -->
    <view class="main-content" :class="{ 'has-photo': photoUrl }">
      <!-- 拍照引导区 -->
      <view class="capture-guide" v-if="!photoUrl">
        <view class="guide-header">
          <image class="camera-icon" src="/static/images/camera-icon.png" mode="aspectFit" />
          <text class="guide-title">拍摄您的房间</text>
          <text class="guide-subtitle">获得AI设计师的专业建议</text>
        </view>
        
        <!-- 快捷场景选择 -->
        <view class="scene-selector">
          <text class="scene-title">快速体验</text>
          <view class="scene-grid">
            <view class="scene-item" 
              v-for="(room, index) in roomExamples" 
              :key="index" 
              @click="selectExampleRoom(room)">
              <image class="scene-image" :src="room.imageUrl" mode="aspectFill" />
              <view class="scene-info">
                <text class="scene-name">{{room.name}}</text>
                <text class="scene-tag">推荐</text>
              </view>
              <view class="scene-mask"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 预览区域 -->
      <view class="preview-area" v-if="photoUrl">
        <image :src="photoUrl" mode="aspectFill" class="preview-image" />
        <view class="preview-overlay" v-if="isAnalyzing">
          <view class="analyzing-box">
            <view class="loading-ring"></view>
            <text class="analyzing-text">AI分析中</text>
            <view class="analyzing-progress">
              <view class="progress-track">
                <view class="progress-bar" :style="{ width: analyzeProgress + '%' }"></view>
              </view>
              <text class="progress-text">{{analyzeProgress}}%</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮区 -->
      <view class="action-area" :class="{ 'with-preview': photoUrl }">
        <view class="action-buttons" v-if="!photoUrl">
<!--          <button class="primary-btn camera-btn" @click="openCamera">
            <text class="btn-icon">📸</text>
            <text>立即拍摄</text>
          </button> -->
		  <button class="secondary-btn album-btn" @click="chooseFromAlbum">
		    <text class="btn-icon">📸️</text>
		    <text>立即拍摄</text>
		  </button>
          <button class="secondary-btn album-btn" @click="chooseFromAlbum">
            <text class="btn-icon">🖼️</text>
            <text>从相册选择</text>
          </button>
        </view>
        <button class="continue-btn" v-if="photoUrl" @click="continueDesign">
          继续设计
          <text class="btn-arrow">→</text>
        </button>
      </view>
    </view>

    <!-- 拍摄提示弹窗 -->
    <view class="tips-modal" v-if="showPhotoTips">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">拍摄技巧</text>
          <text class="close-btn" @click="closeTips">×</text>
        </view>
        <view class="tips-list">
          <view class="tip-item">
            <image class="tip-icon" src="/static/images/tip-light.png" mode="aspectFit" />
            <view class="tip-content">
              <text class="tip-title">光线充足</text>
              <text class="tip-desc">选择自然光充足的时间拍摄</text>
            </view>
          </view>
          <view class="tip-item">
            <image class="tip-icon" src="/static/images/tip-angle.png" mode="aspectFit" />
            <view class="tip-content">
              <text class="tip-title">角度合适</text>
              <text class="tip-desc">包含墙面、地面等关键区域</text>
            </view>
          </view>
          <view class="tip-item">
            <image class="tip-icon" src="/static/images/tip-clean.png" mode="aspectFit" />
            <view class="tip-content">
              <text class="tip-title">画面整洁</text>
              <text class="tip-desc">避免杂物遮挡和人物出现</text>
            </view>
          </view>
        </view>
        <view class="tip-example">
          <image class="example-image" src="/static/images/毛坯房图片.png" mode="aspectFit" />
          <text class="example-text">示例图片</text>
        </view>
        <button class="confirm-btn" @click="closeTips">知道了</button>
      </view>
      <view class="modal-mask" @click="closeTips"></view>
    </view>
  </view>
</template>

<style lang="scss">
.container {
  min-height: 100vh;
  background: linear-gradient(to bottom, #f8f9fa, #ffffff);
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  position: sticky;
  top: 0;
  z-index: 100;

  .nav-left, .nav-right {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .nav-icon {
    font-size: 44rpx;
    color: #333;
  }

  .nav-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .help-icon {
    width: 48rpx;
    height: 48rpx;
    line-height: 48rpx;
    text-align: center;
    background: #f0f0f0;
    border-radius: 24rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.main-content {
  min-height: calc(100vh - 128rpx);
  padding: 32rpx;
  display: flex;
  flex-direction: column;

  &.has-photo {
    padding: 0;
  }
}

.capture-guide {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .guide-header {
    text-align: center;
    padding: 48rpx 0;

    .camera-icon {
      width: 120rpx;
      height: 120rpx;
      margin-bottom: 24rpx;
    }

    .guide-title {
      font-size: 40rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 16rpx;
      display: block;
    }

    .guide-subtitle {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.scene-selector {
  flex: 1;
  padding: 32rpx 0;

  .scene-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }

  .scene-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24rpx;
  }

  .scene-item {
    position: relative;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
    aspect-ratio: 3/4;
    
    .scene-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .scene-info {
      position: absolute;
      left: 20rpx;
      right: 20rpx;
      bottom: 20rpx;
      z-index: 2;
      
      .scene-name {
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;
        margin-bottom: 8rpx;
        display: block;
      }

      .scene-tag {
        display: inline-block;
        padding: 4rpx 12rpx;
        background: rgba(7, 193, 96, 0.9);
        border-radius: 8rpx;
        font-size: 24rpx;
        color: #fff;
      }
    }

    .scene-mask {
      position: absolute;
      inset: 0;
      background: linear-gradient(to top, rgba(0,0,0,0.5), transparent);
      pointer-events: none;
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

.preview-area {
  flex: 1;
  position: relative;
  background: #000;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .preview-overlay {
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;

    .analyzing-box {
      text-align: center;
      padding: 48rpx;

      .loading-ring {
        width: 96rpx;
        height: 96rpx;
        border: 4rpx solid rgba(255, 255, 255, 0.2);
        border-top-color: #07c160;
        border-radius: 50%;
        margin: 0 auto 32rpx;
        animation: spin 1s linear infinite;
      }

      .analyzing-text {
        font-size: 36rpx;
        color: #fff;
        margin-bottom: 32rpx;
        display: block;
      }

      .analyzing-progress {
        width: 400rpx;
        
        .progress-track {
          height: 6rpx;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 3rpx;
          overflow: hidden;
          margin-bottom: 12rpx;

          .progress-bar {
            height: 100%;
            background: #07c160;
            transition: width 0.3s linear;
          }
        }

        .progress-text {
          font-size: 24rpx;
          color: rgba(255, 255, 255, 0.7);
        }
      }
    }
  }
}

.action-area {
  padding: 32rpx;
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  box-shadow: 0 -4rpx 24rpx rgba(0, 0, 0, 0.05);

  &.with-preview {
    background: rgba(0, 0, 0, 0.8);
    backdrop-filter: blur(10px);
  }

  .action-buttons {
    display: flex;
    gap: 24rpx;

    button {
      flex: 1;
      height: 96rpx;
      border-radius: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      
      .btn-icon {
        font-size: 40rpx;
        margin-right: 12rpx;
      }
    }

    .primary-btn {
      background: #07c160;
      color: #fff;
      box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.25);
    }

    .secondary-btn {
      background: #f5f5f5;
      color: #333;
    }
  }

  .continue-btn {
    width: 100%;
    height: 96rpx;
    background: linear-gradient(45deg, #07c160, #00b386);
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
    border-radius: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.25);

    .btn-arrow {
      margin-left: 12rpx;
      font-size: 36rpx;
    }
  }
}

.tips-modal {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;

  .modal-content {
    width: 600rpx;
    background: #fff;
    border-radius: 24rpx;
    padding: 32rpx;
    position: relative;
    z-index: 1;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;

    .modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .close-btn {
      font-size: 48rpx;
      color: #999;
      padding: 16rpx;
    }
  }

  .tips-list {
    margin-bottom: 32rpx;

    .tip-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;

      .tip-icon {
        width: 64rpx;
        height: 64rpx;
        margin-right: 20rpx;
      }

      .tip-content {
        flex: 1;

        .tip-title {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 4rpx;
          display: block;
        }

        .tip-desc {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }

  .tip-example {
    border-radius: 16rpx;
    overflow: hidden;
    margin-bottom: 32rpx;

    .example-image {
      width: 100%;
      height: 300rpx;
      background: #f5f5f5;
    }

    .example-text {
      display: block;
      text-align: center;
      font-size: 24rpx;
      color: #999;
      padding: 12rpx 0;
      background: #f9f9f9;
    }
  }

  .confirm-btn {
    width: 100%;
    height: 88rpx;
    background: #07c160;
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    border-radius: 44rpx;
  }

  .modal-mask {
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(4px);
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>

<script setup>
import { ref } from 'vue'

// 状态变量
const photoUrl = ref('')

const generateRequest =ref(
  {
  prompt: '',
  roomImageUrl: ''
  }
)
const isAnalyzing = ref(false)
const analyzeProgress = ref(0)
const showPhotoTips = ref(true)

// 示例房间数据
const roomExamples = ref([
  { name: '现代客厅', imageUrl: 'http://114.55.56.174:19000/house/%E5%AE%A2%E5%8E%85%E5%9B%BE%E7%89%87.png', tag: '热门' },
  { name: '温馨卧室', imageUrl: 'http://114.55.56.174:19000/house/%E7%94%9F%E6%88%90%E5%8D%A7%E5%AE%A4%E5%9B%BE%E7%89%87.png', tag: '推荐' },
  { name: '整洁卫生间', imageUrl: 'http://114.55.56.174:19000/house/%E7%94%9F%E6%88%90%E5%8D%AB%E7%94%9F%E9%97%B4%E5%9B%BE%E7%89%87.png', tag: '新增' },
  { name: '书房空间', imageUrl: 'http://114.55.56.174:19000/house/%E7%94%9F%E6%88%90%E4%B9%A6%E6%88%BF%E5%9B%BE%E7%89%87.png', tag: '精选' }
])

// 返回上一页
const goBack = () => {
  if (photoUrl.value && !isAnalyzing.value) {
    uni.showModal({
      title: '提示',
      content: '确定要放弃当前设计吗？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack()
        }
      }
    })
  } else {
    uni.navigateBack()
  }
}

// 显示拍照说明
const showTips = () => {
  showPhotoTips.value = true
}

// 关闭拍照说明
const closeTips = () => {
  showPhotoTips.value = false
}

// 打开相机
const openCamera = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: (res) => {
      handlePhotoResult(res.tempFilePaths[0])
    },
    fail: (err) => {
      if (err.errMsg.indexOf('cancel') === -1) {
        uni.showToast({
          title: '打开相机失败，请检查权限设置',
          icon: 'none'
        })
      }
    }
  })
}

// 从相册选择并上传图片
const chooseFromAlbum = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['album'],
    success: (res) => {
      console.log('选择的图片信息:', res)
      uni.request({
          url: 'http://localhost:9668/aipaizhao/generateImageFromText', // 替换为实际的API地址
          method: 'POST',
          data: {
            roomImageUrl: "http://114.55.56.174:19000/house/%E5%AE%A2%E5%8E%85%E5%9B%BE%E7%89%87.png",
            prompt: "中式风格的客厅"
          },
          header: {
            'content-type': 'application/json'
          },
          success: (res) => {
            console.log('请求成功:', res)
            if (res.statusCode === 200 && res.data) {
              // 保存生成的图片结果
              uni.setStorageSync('generatedDesign', res.data.imageUrl)
              console.log('图片生成成功:', res.data.imageUrl)
              // 跳转到拍照设计结果页面
              uni.navigateTo({
                url: '/pages/design/photo-result'
              })
            } else {
              console.error('图片生成失败:', res.data)
              uni.showToast({
                title: '生成失败，请重试',
                icon: 'none'
              })
            }
          }})


      // if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      //   // 使用用户实际选择的图片路径
      //   const selectedImagePath = res.tempFilePaths[0];
      //   console.log('选择的图片路径:', selectedImagePath)
        
      //   // 将选择的图片保存到本地存储，以便在其他页面使用
      //   uni.setStorageSync('selectedRoomImage', selectedImagePath)
        
      //   // 显示上传中提示
      //   uni.showLoading({
      //     title: '图片上传中...'
      //   })
        
      //   // 上传图片到MinIO服务器
      //   uni.uploadFile({
      //     url: 'http://localhost:9668/aipaizhao/generateImageFromImage', // MinIO图片上传API地址
      //     filePath: selectedImagePath,
      //     name: 'image', // 根据后端API参数名调整
      //     formData: {
      //       // 可以添加额外的表单数据
      //     },
      //     success: (uploadRes) => {
      //       uni.hideLoading()
      //       console.log('图片上传到MinIO成功:', uploadRes)
            
      //       // 解析上传结果
      //       let result = {}
      //       try {
      //         if (typeof uploadRes.data === 'string') {
      //           result = JSON.parse(uploadRes.data)
      //         } else {
      //           result = uploadRes.data
      //         }
              
      //         // 获取MinIO返回的图片URL
      //         const minioImageUrl = result.imageUrl || result;
      //         console.log('MinIO返回的图片URL:', minioImageUrl)
              
      //         // 跳转到photo-sheji.vue页面，并传递图片路径参数
      //         // uni.navigateTo({
      //         //   url: '/pages/design/photo-sheji?imagePath=' + encodeURIComponent(minioImageUrl || selectedImagePath),
      //         //   success: () => {
      //         //     console.log('成功跳转到设计页面')
      //         //   },
      //         //   fail: (err) => {
      //         //     console.error('跳转失败:', err)
      //         //     uni.showToast({
      //         //       title: '页面跳转失败',
      //         //       icon: 'none'
      //         //     })
      //         //   }
      //         // })
      //       } catch (e) {
      //         console.error('解析MinIO上传结果失败:', e)
      //         uni.showToast({
      //           title: '图片上传失败',
      //           icon: 'none'
      //         })
      //       }
      //     },
      //     fail: (err) => {
      //       uni.hideLoading()
      //       console.error('图片上传到MinIO失败:', err)
      //       uni.showToast({
      //         title: '图片上传失败',
      //         icon: 'none'
      //       })
      //     }
      //   })
      // } else {
      //   uni.showToast({
      //     title: '获取图片失败',
      //     icon: 'none'
      //   })
      // }
    },
    fail: (err) => {
        调用后端接口
  
      console.error('选择图片失败:', err)
      if (err.errMsg.indexOf('cancel') === -1) {
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    }
  })
}

// 处理照片结果
const handlePhotoResult = (tempFilePath) => {
  photoUrl.value = tempFilePath

}

// 选择示例房间
const selectExampleRoom = (room) => {
  photoUrl.value = room.imageUrl
  generateRequest.value.roomImageUrl = room.imageUrl
  generateRequest.value.prompt = room.name
  startAnalyzing()
}

// 开始分析房间
const startAnalyzing = () => {
  isAnalyzing.value = true
  analyzeProgress.value = 0
  
  // 模拟进度更新
  const progressInterval = setInterval(() => {
    if (analyzeProgress.value < 90) {
      analyzeProgress.value += Math.random() * 10
    }
  }, 500)

  console.log(generateRequest.value)
  // 调用后端接口
  uni.request({
    url: 'http://localhost:9668/aipaizhao/generateImageFromText',
    method: 'POST',
    data: {
      prompt: generateRequest.value.prompt,
      roomImageUrl: generateRequest.value.roomImageUrl
    },
    header: {
      'content-type': 'application/json'
    },
    success: (res) => {
      console.log('请求成功:', res)
      if (res.statusCode === 200 && res.data) {
        // 设置进度为100%
        analyzeProgress.value = 100
        setTimeout(() => {
          isAnalyzing.value = false
          // 保存生成的图片结果
          uni.setStorageSync('generatedDesign', res.data)
          console.log('图片生成成功:', res)
          // 跳转到拍照设计结果页面
          uni.navigateTo({
            url: '/pages/design/photo-result'
          })
        }, 500) // 等待进度条动画完成
      } else {
        isAnalyzing.value = false
        console.error('图片生成失败:', res.data)
        uni.showToast({
          title: '生成失败，请重试',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      isAnalyzing.value = false
      console.error('请求失败:', err)
      uni.showToast({
        title: '生成失败，请重试',
        icon: 'none'
      })
    },
    complete: () => {
      clearInterval(progressInterval)
    }
  })
}

// 继续设计
const continueDesign = () => {
  if (!photoUrl.value) {
    uni.showToast({
      title: '请先拍照或选择图片',
      icon: 'none'
    })
    return
  }
  
  if (isAnalyzing.value) {
    uni.showToast({
      title: '正在分析房间，请稍候',
      icon: 'none'
    })
    return
  }
  
  // 跳转到拍照设计结果页面
  uni.navigateTo({
    url: '/pages/design/photo-result',
    success: () => {
      // 将生成的图片保存到缓存中
      uni.setStorageSync('generatedDesign', photoUrl.value)
    }
  })
}
</script> 